/**
 * 写文件
 */
import common from '../../tnxet-common.js';
import util from '../main-util.js';
import fs from 'fs';
import path from 'path';

export default {
    name: common.event.file.write,
    listen(filePath, data) {
        return new Promise((resolve, reject) => {
            if (filePath) {
                filePath = util.file.getAbsolutePathBasedOnApp(filePath);
                const dir = path.dirname(filePath);
                fs.mkdirSync(dir, {recursive: true});
                fs.writeFile(filePath, data, common.event.file.encoding, error => {
                    if (error) {
                        reject(error);
                    } else {
                        resolve();
                    }
                });
            } else {
                reject('Invalid filePath: ' + filePath);
            }
        });
    },
}
